<?php

namespace app\common\service;

use app\common\service\Base;
use app\common\service\Order as OrderService;
use app\common\service\OrderSize as OrderSizeService;
use app\common\service\OrderMaterialItem as OrderMaterialItemService;
use app\common\service\MaterialStockCutting as MaterialStockCuttingService;

class OrderUser extends Base
{

	/**
	 * 根据ID获取记录信息
	 *
	 * @author KING
	 * @date 2020年7月9日
	 *
	 * @param integer $id
	 * @param string $field
	 * @return array
	 */
	public function getInfoById($id, $field='*') {
		if (empty($id)) return [];
		return db('order_user')->where('mid', $id)->field($field)->findOrEmpty();
	}

	/**
	 * 根据订单号获取尺码列表
	 *
	 * @author KING
	 * @date 2020年7月13日
	 *
	 * @param integer $orderId
	 * @param string $field
	 * @return array
	 */
	public function getListByOrderId($orderId, $field='*') {
		if (empty($orderId)) return [];
		return db('order_user')->where('order_id', $orderId)->field($field)->order('zhahao asc')->select();
	}
	/**
	 * 根据订单号获取尺码列表
	 *
	 * @author KING
	 * @date 2020年7月13日
	 *
	 * @param integer $orderId
	 * @param integer $chuanghao
	 * @param string $field
	 * @return array
	 */
	public function getListByOrderIdChuanghao($orderId,$chuanghao, $field='*') {
		if (empty($orderId)) return [];
		$where=[
			'order_id'=>$orderId,
			'chuanghao'=>$chuanghao
		];
		return db('order_user')->where($where)->field($field)->order('zhahao asc')->select();
	}
	/**
	 * 更新订单
	 *
	 * @author KING
	 * @date 2020年7月1日
	 *
	 * @param array $data
	 * @param array $where
	 * @return number
	 */
	public function updateInfo($data, $where=[]) {
		$data['update_time'] = time();
		return db('order_user')->where($where)->update($data);
	}

	/**
	 * 生成扎数
	 *
	 * @author King
	 * @date 2020年9月3日
	 *
	 * @param integer $orderId
	 * @param bool $force		是否强制重新生成
	 * @param array $zhahaoJinpengDel	金鹏需删除的扎号
	 */
	public function makeBundle($orderId, $force=false, &$zhahaoJinpengDel=[]) {
		$orderService = new OrderService();
		$orderSizeService = new OrderSizeService();
		$orderMaterialItemService = new OrderMaterialItemService();
		$materialStockCuttingService = new MaterialStockCuttingService();

		$oInfo = $orderService->getInfoById($orderId);
		if(empty($oInfo)) return false;
		$omInfo = db('order_material')->where('order_id', $orderId)->where('caichuang_standard', 1)->findOrEmpty();
		if (empty($omInfo)) return false;

		$mid = $omInfo['mid'];
		$clientOrdernum = $omInfo['client_ordernum'];

		$omiList = $orderMaterialItemService->getListByOrderMaterialId($mid);
		$mscInfo = $materialStockCuttingService->getInfoByMaterialId($orderId, $omInfo['material_id']);
		if ($mscInfo) {
			array_push($omiList, $mscInfo);
		}

		$osLowMap = [];	// 低层尺码件数
		$osHeightMap = [];	// 高层尺码件数
		$osList = $orderSizeService->getListByOrderId($orderId);
		foreach ($osList as $v) {
			$lowCount = arrayGet($v['wheat_low_count_detail'], $mid, 0);
			$lowBundle = intval(arrayGet($v['wheat_low_bundle_detail'], $mid, 0));
			if ($lowCount > 0) {
				$lowBundle = $lowBundle < 2 ? 1 : $lowBundle;
				$lowBundle = $lowBundle > $lowCount ? $lowCount : $lowBundle;
				$lowCountArr = array_chunk(array_fill(0, $lowCount, 1), $lowBundle);
				$osLowMap[$v['size_name']] = $lowCountArr;
			}

			$heightCount = arrayGet($v['wheat_height_count_detail'], $mid, 0);
			$heightBundle = intval(arrayGet($v['wheat_height_bundle_detail'], $mid, 0));
			if ($heightCount > 0) {
				$heightBundle = $heightBundle < 2 ? 1 : $heightBundle;
				$heightBundle = $heightBundle > $heightCount ? $heightCount : $heightBundle;
				$heightCountArr = array_chunk(array_fill(0, $heightCount, 1), $heightBundle);
				$osHeightMap[$v['size_name']] = $heightCountArr;
			}
		}

		$ouArr = [];
		$zhahao = 1;

		// 低层
		foreach ($osLowMap as $sizeName => $countData) {
			foreach ($countData as $countArr) {
				foreach ($omiList as $k => $v) {
					if ($v['caichuang_t_wheat_low'] > 0) {
						$clothNum = arrayGet($v, 'cloth_num', 0) ? arrayGet($v, 'cloth_num', 0) : 999999;
						$ouArr[] = [
							'zhahao' => $zhahao,
							'jianshu' => $v['caichuang_t_wheat_low'] * count($countArr),
							'size_name' => $sizeName,
							'height_low' => 2,
							'cloth_num' => $clothNum,
						];
						$zhahao++;
					}
				}
			}
		}

		// 高层
		foreach ($osHeightMap as $sizeName => $countData) {
			foreach ($countData as $countArr) {
				foreach ($omiList as $k => $v) {
					if ($v['caichuang_t_wheat_height'] > 0) {
						$clothNum = arrayGet($v, 'cloth_num', 0) ? arrayGet($v, 'cloth_num', 0) : 999999;
						$ouArr[] = [
							'zhahao' => $zhahao,
							'jianshu' => $v['caichuang_t_wheat_height'] * count($countArr),
							'size_name' => $sizeName,
							'height_low' => 1,
							'cloth_num' => $clothNum
						];
						$zhahao++;
					}
				}
			}
		}

		$ouHash = md5(json_encode($ouArr));
		$key = BUNDLE_HASH . $clientOrdernum;
		if (cache($key) != $ouHash || $force) {
			$orderUserOriMap = db('order_user')->where('order_id', $orderId)->column('jinpeng_status,jinpeng_qty,jinpeng_size_name,jinpeng_chuanghao,mid,chuanghao,size_name,jianshu,create_time', 'zhahao');
			$zhahaoOri = array_keys($orderUserOriMap); // 原来扎号
			$zhahaoDel = array_diff($zhahaoOri, array_column($ouArr, 'zhahao')); // 实际删除的扎
			$zhahaoJinpeng = db('order_user')->where('order_id', $orderId)->where('jinpeng_status', 1)->column('zhahao'); // 金鹏已同步的扎号
			$zhahaoJinpengDel = array_intersect($zhahaoDel, $zhahaoJinpeng);
			db('order_user')->where('order_id', $orderId)->delete();
			$baseArr = [
				'factory_id' => $oInfo['factory_id'],
				'order_id' => $orderId,
				'client_ordernum' => $oInfo['client_ordernum'],
				'chuanghao' => $oInfo['caichuang_chuanghao'],
				'create_time' => time(),
				'update_time' => time(),
			];
			foreach ($ouArr as $v) {
				$insData = array_merge($v, $baseArr);

				// 处理金鹏系统对应的字段信息start
				if (isset($orderUserOriMap[$insData['zhahao']]) && $orderUserOriMap[$insData['zhahao']]['jinpeng_status'] == 1) {
					$zhaInfo = $orderUserOriMap[$insData['zhahao']];
					$insData['jinpeng_qty'] = $zhaInfo['jinpeng_qty'];
					$insData['jinpeng_chuanghao'] = $zhaInfo['jinpeng_chuanghao'];
					$insData['jinpeng_size_name'] = $zhaInfo['jinpeng_size_name'];
					if($zhaInfo['jinpeng_chuanghao'] == $insData['chuanghao'] && $zhaInfo['jinpeng_qty'] == $insData['jianshu'] && $zhaInfo['jinpeng_size_name'] == $insData['size_name']) $insData['jinpeng_status'] = 1;
				}
				// 处理金鹏系统对应的字段信息end

				db('order_user')->insert($insData);
			}

			cache($key, $ouHash, 864000);
		}
		return true;
	}
	/**
	 * 获取实裁数
	 *
	 * @author 飞燕
	 * @date 2021年5月14日
	 *
	 * @param integer|array $orderIds	订单ID
	 * @return number
	 */
	public function getShicaiCount($orderIds) {
		if (is_array($orderIds)) {
			$where[] = ['order_id', 'in', $orderIds];
		} else {
			$where[] = ['order_id', '=', $orderIds];
		}
		return db('order_user')->where($where)->sum('jianshu');
	}
}